	<template>
		<nav class="order-nav">
			<ul class="nav-list">
				<li class="nav-item" :class="{ active: currentStatus === 'all' }" @click="selectOrderStatus('all')">全部</li>
				<li class="nav-item" :class="{ active: currentStatus === 'unpaid' }" @click="selectOrderStatus('unpaid')">
					待支付</li>
				<li class="nav-item" :class="{ active: currentStatus === 'pending' }"
					@click="selectOrderStatus('pending')">待发货</li>
				<li class="nav-item" :class="{ active: currentStatus === 'received' }"
					@click="selectOrderStatus('received')">待收货</li>
				<li class="nav-item" :class="{ active: currentStatus === 'refund' }" @click="selectOrderStatus('refund')">
					退款/售后</li>
				<li class="nav-item" :class="{ active: currentStatus === 'appraise' }"
					@click="selectOrderStatus('appraise')">
					待评价</li>
			</ul>
		</nav>
		<view class="store-list">
			<!-- 遍历商店列表 -->
			<view v-for="(store, storeIndex) in filteredStores" :key="storeIndex" class="store">
				<view class="store-header">
					<image class="store-logo" :src="store.logo"></image>
					<!-- 商店名称 -->
					<text class="store-name">{{ store.sellerName }}</text>
					<uni-icons type="forward" size="18" class="right-arrow-icon"></uni-icons>
					<text class="store-status">{{ store.status }}</text>
				</view>
				<!-- 遍历商店中的商品列表 -->
				<view v-for="(item, itemIndex) in store.cartItems" :key="itemIndex" class="item-row"
					@click="goToStoreDetail(store.sellerID)">
					<!-- 商品信息 -->
					<view class="item-info">
						<!-- 商品图片 -->
						<image class="item-image" :src="item.image"></image>
						<!-- 商品名称、价格和数量 -->
						<view class="item-details">
							<!-- 商品名称 -->
							<text class="item-name">
								<view class="goods_name">{{ item.name }}</view>
							</text>
							<!-- 商品价格和数量容器 -->
							<view class="item-pricing-quantity">
								<!-- 商品价格 -->
								<text class="item-price">￥{{ item.price }}</text>
								<!-- 商品购买数量 -->
								<text class="item-quantity">x{{ item.quantity }}</text>
							</view>
						</view>
					</view>

				</view>
				<view class="store-actions">
					<!-- 根据订单状态显示不同的按钮 -->
					<button v-if="store.orderStatus!=='unpaid'&&store.orderStatus!=='refund'" class="add-to-cart-btn"
						@click="goToRefund(store.sellerID,store.cartItems[0].id,store.orderNum,calculateTotal(store.cartItems).toFixed(2),store.orderStatus)">
						<text>退款</text>
					</button>

					<button v-if="store.orderStatus==='appraise'" class="reorder-btn"
						@click="handleClick(store.sellerID, store.cartItems[0].id)">
						评价
					</button>

					<button v-if="store.status === '交易成功'" class="add-to-cart-btn"
						@click="addToCart(storeIndex, itemIndex)">
						<text>加入购物车</text>
					</button>
					<button v-if="store.status === '交易成功'" class="reorder-btn" @click="reorder(store)">
						再买一单
					</button>
					<button v-if="store.orderStatus === 'received'" class="add-to-cart-btn"
						@click="addToCart(storeIndex, itemIndex)">
						<text>查看物流</text>
					</button>
					<button v-if="store.orderStatus === 'received'" class="reorder-btn"
						@click="confirmOrder(store.orderNum)">
						确认收货
					</button>
					<button v-if="store.orderStatus === 'unpaid'" class="add-to-cart-btn">
						<text>取消订单</text>
					</button>
					<button v-if="store.orderStatus === 'unpaid'" class="reorder-btn" @click="pay(store.orderNum)">
						继续付款
					</button>

				</view>
				<view class="store-footer">
					<!-- 计算并显示实付款 -->
					<text v-if="store.orderStatus === 'unpaid'" class="actual-payment">需付款:
						￥{{ calculateTotal(store.cartItems).toFixed(2) }}</text>
					<text v-else class="actual-payment">实付款: ￥{{ calculateTotal(store.cartItems).toFixed(2) }}</text>
				</view>
			</view>
		</view>
	</template>
	<script>
		import axios from 'axios';
		import service from '../../utils/request.js';
		export default {

			data() {
				return {
					userID: localStorage.getItem("userID"),
					currentStatus: 'all', //导航栏状态，当前为全部
					stores: [{
						name: '',
						cartItems: [{
							id: null,
							name: '',
							price: null,
							image: '../../static/images/pet/193619.png',
							quantity: null,

						}, ]
					}, ],
				};
			},
			computed: {
				totalAmounts() {
					// 计算每个商店的总金额
					return this.stores.map(store => {
						return store.cartItems.reduce((total, item) => {
							return total + item.price * item.quantity;
						}, 0);
					});
				},
				filteredStores() {
					if (this.currentStatus === 'all') {
						return this.stores;
					} else {
						return this.stores.filter(store => store.orderStatus === this.currentStatus);
					}
				}
			},
			onLoad(option) {
				this.currentStatus = option.status || 'all';
				this.fetchOrders(this.currentStatus);
			},
			methods: {
				async getOrderData() {
					try {
						// 获取商品及其商家信息
						const response = await service.get('/order/user/' + this.userID);
						console.log('数据:', response);

						// 转换后端数据为前端所需格式
						const stores = this.transformData(response.data);

						// 将转换后的数据赋值给组件的状态，以便在前端使用
						this.stores = stores;

					} catch (error) {
						console.error('获取数据失败:', error);
					}
				},
				async pay(orderNum) {
					try {
						// 构建包含查询参数的URL
						const url = `/order/pay?orderNo=${encodeURIComponent(orderNum)}`;
						// 发起GET请求
						const response = await service.get(url);
						console.log('数据:', response);
						this.getOrderData();
					} catch (error) {
						console.error('获取数据失败:', error);
					}
				},
				transformData(data) {
					// 使用Map来存储订单号和商家ID的组合作为键，商家信息和商品列表作为值
					const ordersMap = new Map();

					// 遍历每个订单
					data.forEach(order => {
						// 检查是否已经添加了这个订单号和商家ID的组合
						const orderSellerKey = `${order.orderNum}_${order.sellerID}`;
						let orderEntry = ordersMap.get(orderSellerKey);
						if (!orderEntry) {
							// 如果这个订单号和商家ID的组合不存在，则创建一个新的商家对象
							orderEntry = {
								orderNum: order.orderNum,
								sellerID: order.sellerID,
								sellerName: order.sellerName,
								orderStatus: order.orderStatus,
								logo: '../../static/images/pet/193619.png', // 假设的logo路径
								cartItems: []
							};
							ordersMap.set(orderSellerKey, orderEntry);
						}

						// 遍历订单中的商品
						order.items.forEach(item => {
							// 将商品添加到订单号和商家ID组合的cartItems数组中
							orderEntry.cartItems.push({
								id: item.goodsID,
								name: item.goodsName,
								price: item.price,
								image: '../../static/images/pet/193619.png', // 假设的图片路径
								quantity: item.num
							});
						});
					});

					// 将Map转换为数组，以便在前端使用
					return Array.from(ordersMap.values());
				},
				calculateTotal(items) {
					return items.reduce((total, item) => {
						return total + (item.price * item.quantity);
					}, 0);
				},
				selectOrderStatus(status) {
					this.currentStatus = status;
				},
				// 将商品加入购物车的方法
				addToCart(storeIndex, itemIndex) {
					// 这里是加入购物车的逻辑
					console.log(`加入购物车：商店 ${storeIndex} 中的商品 ${itemIndex}`);
					this.$router.push({
						path: '/pages/cart/cart'
					});
				},
				reorder(store) {
					// 这里是再买一单的逻辑
					console.log(`再买一单：商店 ${store.name}`);
				},
				// 再买一单的方法
				async confirmOrder(orderNum) {
					try {
						// 构建包含查询参数的URL
						const url = `/order/confirm?orderNo=${encodeURIComponent(orderNum)}`;
						// 发起GET请求
						const response = await service.get(url);
						console.log('数据:', response);
						this.getOrderData();
					} catch (error) {
						console.error('获取数据失败:', error);
					}
				},
				// 跳转至详情页面
				goToStoreDetail(storeId) {
					this.$router.push({
						path: '/pages/order-detail/order-detail'
					});
				},
				goToRefund(sellerID, itemId, orderNum, price,status1) {
					if (!sellerID || !itemId) {
						console.error("商品ID或商家ID未定义");
						return;
					}
					// 将商家ID和商品ID存储到本地存储中
					uni.setStorageSync('goodsID', itemId);
					uni.setStorageSync('sellerID', sellerID);
					uni.setStorageSync('orderNum', orderNum);
					uni.setStorageSync('price', price);
					uni.setStorageSync('status1', status1);
					// 使用导航方法跳转并传递参数
					uni.navigateTo({
						url: `/pages/refund/refund?goodsID=${itemId}&sellerID=${sellerID}&orderNum=${orderNum}&price=${price}&status1=${status1}`
					});
				},
				handleClick(sellerID, itemId) {
					console.log('点击的商家ID:', sellerID);
					console.log('点击的商品ID:', itemId);
					// 跳转到评价页面，并传递商品ID和商家ID
					this.goToAppraise(sellerID, itemId);
				},
				goToAppraise(sellerID, itemId) {
					if (!sellerID || !itemId) {
						console.error("商品ID或商家ID未定义");
						return;
					}
					// 将商家ID和商品ID存储到本地存储中
					uni.setStorageSync('goodsID', itemId);
					uni.setStorageSync('sellerID', sellerID);

					// 使用导航方法跳转并传递参数
					uni.navigateTo({
						url: `/pages/appraise/appraise?goodsID=${itemId}&sellerID=${sellerID}`
					});
				},
				getUserIDFromLocalStorage() {
					const userID = localStorage.getItem('userID');
					// 将字符串转换为数字
					return userID ? parseInt(userID, 10) : null;
				},
			},
			onShow() {
				this.getOrderData();
				this.userID = this.getUserIDFromLocalStorage();
			},
			filters: {
				formatPrice(value) {
					return value.toFixed(2);
				},
			},

		};
	</script>

	<style lang="scss" scoped>
		@use "order";
	</style>